package core.bmp.worker;

import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import core.bmp.Bmp;
import core.bmp.utils.MathUtil;

public class RotateWoker {

	public static void rotateImage(File src, File dst, double angle) {
		BufferedImage bufferedimage;
		try {
			bufferedimage = ImageIO.read(src); // 读入文件
			int w = bufferedimage.getWidth();
			int h = bufferedimage.getHeight();
			int type = bufferedimage.getColorModel().getTransparency();

			int width = (int) Math.ceil(h * MathUtil.sinAbs(angle) + w * MathUtil.cosAbs(angle));
			int height = (int) Math.ceil(h * MathUtil.cosAbs(angle) + w * MathUtil.sinAbs(angle));

			// AffineTransform.getTranslateInstance(double tx, double ty)
			// 返回表示平移变换的变换
			AffineTransform trans = new AffineTransform();
			trans.setToTranslation((width - w) / 2, (height - h) / 2);
			trans.rotate(Math.toRadians(angle), w / 2, h / 2);
			BufferedImage relImg = new BufferedImage(width, height, type);
			Graphics2D g2d = relImg.createGraphics(); // 设置背景为透明
			relImg = g2d.getDeviceConfiguration().createCompatibleImage(width, height);
			g2d.dispose();
			g2d = relImg.createGraphics();
			g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
			g2d.setTransform(trans);
			g2d.drawImage(bufferedimage, 0, 0, null);
			g2d.dispose();

			ImageIO.write(relImg, "bmp", dst);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] argbs) {
		rotateImage(Bmp.BMP_LENA, new File(Bmp.DIR_FILE, RotateWoker.class.getSimpleName() + ".bmp"), 60);
	}

}
